<?php

namespace App\Http\Controllers\Api;

use App\Models\HhmCoinCorpQuota;
use App\Models\HhmCoinCorpQuotaFlow;
use App\Models\Member;
use App\Models\BreedUserCoinQuota;
use App\Models\BreedCoinQuotaFlow;
use App\Models\Store;
use App\Models\HhmCoinSet;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use InvalidArgumentException;

class CreditController extends BaseApiController
{
    /**
     * 授信激活默认时长（天）
     */
    private const ACTIVATION_DURATION_DAYS = 30;

    /**
     * 缓存不同 uniacid 的激活时长
     *
     * @var array<int, int>
     */
    private static array $activeDaysCache = [];

    /**
     * 额度流水类型：0=授信激活，30=转出
     */
    private const FLOW_TYPE_ACTIVATION = 0;
    private const FLOW_TYPE_TRANSFER   = 30;

    /**
     * 获取授信激活可用天数
     */
    private function getCorpQuotaActiveDays(int $uniacid = 1): int
    {
        if (! isset(self::$activeDaysCache[$uniacid])) {
            $setting = HhmCoinSet::query()
                ->where('uniacid', $uniacid)
                ->orderByDesc('id')
                ->first();

            $days = $setting && $setting->corp_quota_active_time
                ? (int) $setting->corp_quota_active_time
                : self::ACTIVATION_DURATION_DAYS;

            self::$activeDaysCache[$uniacid] = $days > 0 ? $days : self::ACTIVATION_DURATION_DAYS;
        }

        return self::$activeDaysCache[$uniacid];
    }

    /**
     * 授信功能总览（首页）
     */
    public function dashboard(Request $request): JsonResponse
    {
        try {
            $storeId = (int) $this->getRequiredParam($request, 'store_id', '缺少门店ID');
            $userId  = (int) $this->getParam($request, 'user_id');

            $quota = $this->findOrCreateQuota($storeId);

            $store = Store::find($storeId);
            if (! $store) {
                throw new InvalidArgumentException('门店不存在');
            }

            $member = $userId ? Member::find($userId) : null;

            $data = [
                'user' => [
                    'id'           => $member ? (string) $member->uid : (string) $storeId,
                    'name'         => $member ? ($member->display_name ?? ('用户' . $member->uid)) : ($store->store_name ?? '门店管理'),
                    'avatar'       => $member ? ($member->avatar ?? '') : '',
                    'memberLevel'  => $member && $member->vip ? ('VIP' . $member->vip) : '门店账号',
                ],
                'store' => [
                    'store_id'   => $storeId,
                    'store_name' => $store->store_name,
                ],
                'order_counts' => [
                    'pending'  => 0,
                    'waiting'  => 0,
                    'done'     => 0,
                    'all'      => 0,
                ],
                'menus' => [
                    [
                        'title' => '门店申请',
                        'icon'  => '🏬',
                        'type'  => 'store',
                        'url'   => '/pages/member/store/index',
                    ],
                    [
                        'title' => '自提点申请',
                        'icon'  => '📍',
                        'type'  => 'pickup',
                        'url'   => '/pages/member/pickup/application',
                    ],
                    [
                        'title' => '置换码',
                        'icon'  => '🔁',
                        'type'  => 'redeem',
                        'url'   => '/pages/member/store/verification-record',
                    ],
                    [
                        'title' => '授信激活',
                        'icon'  => '🛡️',
                        'type'  => 'credit',
                        'url'   => '/pages/member/credit/activation',
                    ],
                    [
                        'title' => '云仓库存额度',
                        'icon'  => '☁️',
                        'type'  => 'warehouse',
                        'url'   => '/pages/member/credit/warehouse',
                    ],
                ],
                'scenario' => $this->formatActivationScenario($quota),
            ];

            return response()->json([
                'result' => 1,
                'msg'    => '获取成功',
                'data'   => $data,
            ]);
        } catch (InvalidArgumentException $e) {
            return response()->json([
                'result' => 0,
                'msg'    => $e->getMessage(),
                'data'   => [],
            ]);
        } catch (\Throwable $e) {
            return response()->json([
                'result' => 0,
                'msg'    => '请求失败：' . $e->getMessage(),
                'data'   => [],
            ]);
        }
    }

    /**
     * 获取授信激活状态（激活页）
     */
    public function activationStatus(Request $request): JsonResponse
    {
        try {
            $storeId = (int) $this->getRequiredParam($request, 'store_id', '缺少门店ID');

            $quota = $this->findOrCreateQuota($storeId);

            $data = [
                'scenario' => $this->formatActivationScenario($quota),
            ];

            return response()->json([
                'result' => 1,
                'msg'    => '获取成功',
                'data'   => $data,
            ]);
        } catch (InvalidArgumentException $e) {
            return response()->json([
                'result' => 0,
                'msg'    => $e->getMessage(),
                'data'   => [],
            ]);
        } catch (\Throwable $e) {
            return response()->json([
                'result' => 0,
                'msg'    => '请求失败：' . $e->getMessage(),
                'data'   => [],
            ]);
        }
    }

    /**
     * 门店发起授信激活
     */
    public function activate(Request $request): JsonResponse
    {
        try {
            $storeId = (int) $this->getRequiredParam($request, 'store_id', '缺少门店ID');

            $quota = DB::transaction(function () use ($storeId) {
                /** @var HhmCoinCorpQuota $quota */
                $quota = $this->findOrCreateQuota($storeId, true);

                if ((int) $quota->status === 1) {
                    throw new InvalidArgumentException('已提交审核，请耐心等待');
                }

                $quota->status              = 1; // 待审核
                $quota->audit_reject_reason = null;
                $quota->updated_at          = time();
                $quota->apply_at            = time();
                $quota->save();

                return $quota->refresh();
            });

            return response()->json([
                'result' => 1,
                'msg'    => '提交成功，请等待平台审核',
                'data'   => [
                    'scenario' => $this->formatActivationScenario($quota),
                ],
            ]);
        } catch (InvalidArgumentException $e) {
            return response()->json([
                'result' => 0,
                'msg'    => $e->getMessage(),
                'data'   => [],
            ]);
        } catch (\Throwable $e) {
            return response()->json([
                'result' => 0,
                'msg'    => '提交失败：' . $e->getMessage(),
                'data'   => [],
            ]);
        }
    }

    /**
     * 取消授信
     */
    public function cancel(Request $request): JsonResponse
    {
        try {
            $storeId = (int) $this->getRequiredParam($request, 'store_id', '缺少门店ID');

            $quota = DB::transaction(function () use ($storeId) {
                /** @var HhmCoinCorpQuota $quota */
                $quota = $this->findOrCreateQuota($storeId, true);

                $scenario = $this->formatActivationScenario($quota);
                if (empty($scenario['showCancelButton'])) {
                    throw new InvalidArgumentException('当前状态不可取消授信');
                }

                $quota->status              = 0;
                $quota->stock_status        = 0;
                $quota->switch              = 0;
                $quota->stock_num           = 0;
                $quota->audit_passed_at     = null;
                $quota->audit_reject_reason = null;
                $quota->updated_at          = time();
                $quota->save();

                return $quota->refresh();
            });

            return response()->json([
                'result' => 1,
                'msg'    => '已取消授信',
                'data'   => [
                    'scenario' => $this->formatActivationScenario($quota),
                ],
            ]);
        } catch (InvalidArgumentException $e) {
            return response()->json([
                'result' => 0,
                'msg'    => $e->getMessage(),
                'data'   => [],
            ]);
        } catch (\Throwable $e) {
            return response()->json([
                'result' => 0,
                'msg'    => '操作失败：' . $e->getMessage(),
                'data'   => [],
            ]);
        }
    }

    /**
     * 云仓额度概览
     */
    public function warehouseSummary(Request $request): JsonResponse
    {
        try {
            $storeId = (int) $this->getRequiredParam($request, 'store_id', '缺少门店ID');

            $quota = $this->findOrCreateQuota($storeId);

            $store = Store::select(['id', 'store_name', 'thumb', 'boss_uid', 'uid'])->find($storeId);
            $bossUid = $store ? (int) ($store->boss_uid ?: $store->uid) : 0;
            $bossMember = null;
            $bossProfile = [
                'uid'      => $bossUid,
                'name'     => '',
                'realname' => '',
                'nickname' => '',
                'mobile'   => '',
                'avatar'   => '',
            ];

            if ($bossUid > 0) {
                $bossMember = Member::query()
                    ->select(['uid', 'realname', 'nickname', 'mobile', 'avatar'])
                    ->where('uid', $bossUid)
                    ->first();

                if ($bossMember) {
                    $bossProfile['name']     = $bossMember->realname ?: ($bossMember->nickname ?: ($bossMember->mobile ?: ''));
                    $bossProfile['realname'] = $bossMember->realname ?? '';
                    $bossProfile['nickname'] = $bossMember->nickname ?? '';
                    $bossProfile['mobile']   = $bossMember->mobile ?? '';
                    $bossProfile['avatar']   = $bossMember->avatar ?? '';
                }
            }

            $data = [
                'store' => [
                    'store_id'   => $storeId,
                    'store_name' => $store ? $store->store_name : '',
                    'avatar'     => $store ? ($store->thumb ?? '') : '',
                    'boss_uid'   => $bossUid,
                    'boss'       => $bossProfile,
                ],
                'quota' => $this->formatWarehouseSummary($quota),
            ];

            return response()->json([
                'result' => 1,
                'msg'    => '获取成功',
                'data'   => $data,
            ]);
        } catch (InvalidArgumentException $e) {
            return response()->json([
                'result' => 0,
                'msg'    => $e->getMessage(),
                'data'   => [],
            ]);
        } catch (\Throwable $e) {
            return response()->json([
                'result' => 0,
                'msg'    => '请求失败：' . $e->getMessage(),
                'data'   => [],
            ]);
        }
    }

    /**
     * 云仓额度流水
     */
    public function warehouseFlows(Request $request): JsonResponse
    {
        try {
            $storeId  = (int) $this->getParam($request, 'store_id', 0);
            $userId   = (int) $this->getParam($request, 'user_id', 0);
            $page     = max(1, (int) $this->getParam($request, 'page', 1));
            $pageSize = max(1, min(50, (int) $this->getParam($request, 'page_size', 10)));

            if ($storeId <= 0 && $userId <= 0) {
                throw new InvalidArgumentException('缺少查询用户信息');
            }

            $store = null;
            if ($storeId > 0) {
                $store = Store::select(['id', 'boss_uid', 'uid'])->find($storeId);
                if (! $store) {
                    throw new InvalidArgumentException('门店不存在');
                }
            } elseif ($userId > 0) {
                $store = Store::select(['id', 'boss_uid', 'uid'])->where('uid', $userId)->first();
                if ($store) {
                    $storeId = (int) $store->id;
                }
            }

            $flowIdentifiers = $this->buildStoreFlowIdentifiers($storeId, $store, $userId);
            if (empty($flowIdentifiers)) {
                throw new InvalidArgumentException('暂无可查询的流水标识');
            }

            $query = HhmCoinCorpQuotaFlow::query()
                ->where(function ($builder) use ($flowIdentifiers) {
                    $builder->whereIn('send_user', $flowIdentifiers)
                        ->orWhereIn('rec_user', $flowIdentifiers);
                })
                ->orderByDesc('id');

            $total  = $query->count();
            $flows  = $query->forPage($page, $pageSize)->get();

            return response()->json([
                'result' => 1,
                'msg'    => '获取成功',
                'data'   => [
                    'list' => $this->formatFlows($flows),
                    'pagination' => [
                        'page'       => $page,
                        'page_size'  => $pageSize,
                        'total'      => $total,
                        'total_page' => (int) ceil($total / $pageSize),
                    ],
                ],
            ]);
        } catch (InvalidArgumentException $e) {
            return response()->json([
                'result' => 0,
                'msg'    => $e->getMessage(),
                'data'   => [],
            ]);
        } catch (\Throwable $e) {
            return response()->json([
                'result' => 0,
                'msg'    => '请求失败：' . $e->getMessage(),
                'data'   => [],
            ]);
        }
    }

    /**
     * 搜索可转出会员
     */
    public function searchTransferMembers(Request $request): JsonResponse
    {
        try {
            $keyword = trim((string) $this->getParam($request, 'keyword', ''));
            if ($keyword === '') {
                throw new InvalidArgumentException('请输入要搜索的UID');
            }

            $uid = (int) $keyword;
            if ($uid <= 0) {
                throw new InvalidArgumentException('请输入有效的UID');
            }

            $member = Member::query()
                ->where('uid', $uid)
                ->select(['uid', 'realname', 'nickname', 'mobile', 'avatar'])
                ->first();

            $memberData = null;
            if ($member) {
                $memberData = [
                    'uid'      => (int) $member->uid,
                    'nickname' => $member->nickname ?? '',
                    'realname' => $member->realname ?? '',
                    'mobile'   => $member->mobile ?? '',
                    'avatar'   => $member->avatar ?? '',
                    'display'  => $member->realname ?: ($member->nickname ?: ($member->mobile ?: ('UID ' . $member->uid))),
                ];
            }

            return response()->json([
                'result' => 1,
                'msg'    => $memberData ? '获取成功' : '未找到该会员',
                'data'   => [
                    'member' => $memberData,
                ],
            ]);
        } catch (InvalidArgumentException $e) {
            return response()->json([
                'result' => 0,
                'msg'    => $e->getMessage(),
                'data'   => [],
            ]);
        } catch (\Throwable $e) {
            return response()->json([
                'result' => 0,
                'msg'    => '请求失败：' . $e->getMessage(),
                'data'   => [],
            ]);
        }
    }

    /**
     * 云仓额度转出
     */
    public function transfer(Request $request): JsonResponse
    {
        try {
            $storeId      = (int) $this->getRequiredParam($request, 'store_id', '缺少门店ID');
            $targetUserId = (int) $this->getRequiredParam($request, 'target_user_id', '缺少接收用户ID');
            $amount       = (float) $this->getRequiredParam($request, 'amount', '缺少转出额度');
            $remark       = (string) $this->getParam($request, 'remark', '');
            $operatorUserId = (int) $this->getParam($request, 'user_id', 0);

            if ($amount <= 0) {
                throw new InvalidArgumentException('转出额度必须大于0');
            }

            $store = Store::select(['id', 'store_name', 'boss_uid', 'uid'])->find($storeId);
            if (! $store) {
                throw new InvalidArgumentException('门店不存在');
            }

            $storeAccountUid = $this->resolveStoreAccountUid($store, $storeId);
            $storeOwner = null;
            if ($storeAccountUid) {
                $storeOwner = Member::query()
                    ->select(['uid', 'realname', 'nickname'])
                    ->find($storeAccountUid);
            }

            $member = Member::query()
                ->select(['uid', 'realname', 'nickname'])
                ->find($targetUserId);

            $quota = DB::transaction(function () use ($storeId, $targetUserId, $amount, $remark, $member, $storeAccountUid, $operatorUserId, $store, $storeOwner) {
                /** @var HhmCoinCorpQuota $quota */
                $quota = $this->findOrCreateQuota($storeId, true);

                if ((int) $quota->status !== 2) {
                    throw new InvalidArgumentException('授信未激活，无法转出');
                }
                if ((int) $quota->stock_status === 1) {
                    throw new InvalidArgumentException('额度已冻结，无法转出');
                }
                if ($quota->stock_num < $amount) {
                    throw new InvalidArgumentException('云仓库存额度不足');
                }

                $oldCoin = (float) $quota->stock_num;
                $quota->stock_num   = round($quota->stock_num - $amount, 2);
                $quota->updated_at  = time();
                $quota->save();

                $userQuota = BreedUserCoinQuota::query()
                    ->where('user_id', $targetUserId)
                    ->lockForUpdate()
                    ->first();

                $targetOldCoin = $userQuota ? (float) $userQuota->num : 0.0;
                $targetNewCoin = round($targetOldCoin + $amount, 2);

                if ($userQuota) {
                    $userQuota->num = $targetNewCoin;
                    $userQuota->updated_at = time();
                    $userQuota->save();
                } else {
                    BreedUserCoinQuota::create([
                        'user_id'    => $targetUserId,
                        'num'        => $amount,
                        'uniacid'    => 1,
                        'created_at' => time(),
                        'updated_at' => time(),
                    ]);
                }

                $memberName = $member ? ($member->nickname ?: ($member->realname ?: '')) : '';
                $remarkText = $remark ?: ('转出给客户，ID:' . $targetUserId . ($memberName ? ('，昵称:' . $memberName) : ''));

                HhmCoinCorpQuotaFlow::create([
                    'send_user'  => $operatorUserId ?: $storeAccountUid ?: $storeId,
                    'rec_user'   => $targetUserId,
                    'num'        => $amount,
                    'uniacid'    => $quota->uniacid,
                    'created_at' => time(),
                    'updated_at' => time(),
                    'remark'     => $remarkText,
                    'old_coin'   => $oldCoin,
                    'new_coin'   => $quota->stock_num,
                    'type'       => self::FLOW_TYPE_TRANSFER,
                ]);

                $storeName = $store ? ($store->store_name ?? '') : '';
                $ownerUid =$operatorUserId ?: $storeAccountUid ?: $storeId;
                $ownerNickname = $storeOwner ? ($storeOwner->nickname ?: ($storeOwner->realname ?: '')) : '';
                $storeRemark = sprintf(
                    '店铺转入，%s，ID:%s，昵称：%s',
                    $storeName ?: '未知店铺',
                    $ownerUid ?: '',
                    $ownerNickname ?: '未知'
                );

                BreedCoinQuotaFlow::create([
                    'send_user'  => $ownerUid,
                    'rec_user'   => $targetUserId,
                    'num'        => $amount,
                    'uniacid'    => $quota->uniacid,
                    'created_at' => time(),
                    'updated_at' => time(),
                    'remark'     => $storeRemark,
                    'old_coin'   => $targetOldCoin,
                    'new_coin'   => $targetNewCoin,
                    'type'       => self::FLOW_TYPE_TRANSFER,
                ]);

                return $quota->refresh();
            });

            return response()->json([
                'result' => 1,
                'msg'    => '转出成功',
                'data'   => [
                    'quota' => $this->formatWarehouseSummary($quota),
                ],
            ]);
        } catch (InvalidArgumentException $e) {
            return response()->json([
                'result' => 0,
                'msg'    => $e->getMessage(),
                'data'   => [],
            ]);
        } catch (\Throwable $e) {
            return response()->json([
                'result' => 0,
                'msg'    => '转出失败：' . $e->getMessage(),
                'data'   => [],
            ]);
        }
    }

    /**
     * 云仓额度还款
     */
    public function repay(Request $request): JsonResponse
    {
        try {
            $storeId = (int) $this->getRequiredParam($request, 'store_id', '缺少门店ID');
            $amount  = (float) $this->getRequiredParam($request, 'amount', '缺少还款额度');
            $remark  = (string) $this->getParam($request, 'remark', '');

            if ($amount <= 0) {
                throw new InvalidArgumentException('还款额度必须大于0');
            }

            $quota = DB::transaction(function () use ($storeId, $amount, $remark) {
                /** @var HhmCoinCorpQuota $quota */
                $quota = $this->findOrCreateQuota($storeId, true);

                if ((int) $quota->status === 0) {
                    throw new InvalidArgumentException('授信未激活，无需还款');
                }

                $oldCoin = (float) $quota->stock_num;
                $quota->stock_num  = round(min($quota->num, $quota->stock_num + $amount), 2);

                if ((int) $quota->stock_status === 1 && $quota->stock_num >= $quota->num) {
                    // 冻结状态且已还满，恢复初始状态但保留激活开关
                    $quota->status       = 0;
                    $quota->stock_status = 0;
                    $quota->switch       = 1;
                }

                $quota->updated_at = time();
                $quota->save();

                HhmCoinCorpQuotaFlow::create([
                    'send_user'  => 0,
                    'rec_user'   => $storeId,
                    'num'        => $amount,
                    'uniacid'    => $quota->uniacid,
                    'created_at' => time(),
                    'updated_at' => time(),
                    'remark'     => $remark ?: '云仓额度还款',
                    'old_coin'   => $oldCoin,
                    'new_coin'   => $quota->stock_num,
                    'type'       => self::FLOW_TYPE_TRANSFER,
                ]);

                return $quota->refresh();
            });

            return response()->json([
                'result' => 1,
                'msg'    => '还款成功',
                'data'   => [
                    'quota' => $this->formatWarehouseSummary($quota),
                ],
            ]);
        } catch (InvalidArgumentException $e) {
            return response()->json([
                'result' => 0,
                'msg'    => $e->getMessage(),
                'data'   => [],
            ]);
        } catch (\Throwable $e) {
            return response()->json([
                'result' => 0,
                'msg'    => '还款失败：' . $e->getMessage(),
                'data'   => [],
            ]);
        }
    }

    /**
     * 平台审核授信
     */
    public function review(Request $request): JsonResponse
    {
        try {
            $storeId   = (int) $this->getRequiredParam($request, 'store_id', '缺少门店ID');
            $status    = (int) $this->getRequiredParam($request, 'status', '缺少审核状态');
            $reason    = (string) $this->getParam($request, 'reason', '');
            $uniacid   = (int) $this->getParam($request, 'uniacid', 1);

            if (! in_array($status, [2, 3, 4], true)) {
                throw new InvalidArgumentException('仅支持审批状态：2=通过，3=冻结，4=驳回');
            }

            $quota = DB::transaction(function () use ($storeId, $status, $reason, $uniacid) {
                /** @var HhmCoinCorpQuota $quota */
                $quota = $this->findOrCreateQuota($storeId, true, $uniacid);

                $now = time();
                if ($status === 2) {
                    $oldCoin = (float) $quota->stock_num;

                    $quota->status          = 2;
                    $quota->stock_status    = 0;
                    $quota->switch          = 1;
                    $quota->audit_passed_at = $now;
                    $quota->audit_reject_reason = null;
                    $quota->stock_num       = $quota->num;
                    $quota->updated_at      = $now;
                    $quota->save();

                    HhmCoinCorpQuotaFlow::create([
                        'send_user'  => 0,
                        'rec_user'   => $storeId,
                        'num'        => $quota->num,
                        'uniacid'    => $quota->uniacid,
                        'created_at' => $now,
                        'updated_at' => $now,
                        'remark'     => '门店授信额度激活',
                        'old_coin'   => $oldCoin,
                        'new_coin'   => $quota->stock_num,
                        'type'       => self::FLOW_TYPE_ACTIVATION,
                    ]);
                } elseif ($status === 3) {
                    $quota->stock_status = 1;
                    $quota->updated_at   = $now;
                    $quota->save();
                } elseif ($status === 4) {
                    $quota->status              = 4;
                    $quota->audit_reject_reason = $reason ?: '审核未通过';
                    $quota->audit_passed_at     = null;
                    $quota->updated_at          = $now;
                    $quota->save();
                }

                return $quota->refresh();
            });

            return response()->json([
                'result' => 1,
                'msg'    => '审核已处理',
                'data'   => [
                    'scenario' => $this->formatActivationScenario($quota),
                ],
            ]);
        } catch (InvalidArgumentException $e) {
            return response()->json([
                'result' => 0,
                'msg'    => $e->getMessage(),
                'data'   => [],
            ]);
        } catch (\Throwable $e) {
            return response()->json([
                'result' => 0,
                'msg'    => '审核失败：' . $e->getMessage(),
                'data'   => [],
            ]);
        }
    }

    /**
     * 根据门店ID获取或创建授信额度记录
     */
    private function findOrCreateQuota(int $storeId, bool $forUpdate = false, int $uniacid = 1): HhmCoinCorpQuota
    {
        $query = HhmCoinCorpQuota::query()->where('store_id', $storeId);

        if ($forUpdate) {
            $query->lockForUpdate();
        }

        $quota = $query->first();
        if ($quota) {
            return $quota;
        }

        return HhmCoinCorpQuota::create([
            'uniacid'       => $uniacid,
            'store_id'      => $storeId,
            'num'           => 1000.00,
            'created_at'    => time(),
            'updated_at'    => time(),
            'stock_num'     => 0,
            'status'        => 0,
            'stock_status'  => 0,
            'switch'        => 0,
            'audit_passed_at' => null,
            'audit_reject_reason' => null,
        ]);
    }

    /**
     * 组装激活页场景数据
     */
    private function formatActivationScenario(HhmCoinCorpQuota $quota): array
    {
        $statusTextMap = [
            0 => '未激活',
            1 => '待审核',
            2 => '已激活',
            3 => '已冻结',
            4 => '审核不通过',
        ];

        $statusCode         = (int) $quota->status;
        $warehouseStatus    = (int) $quota->stock_status;
        $storeStatusText = $statusTextMap[$statusCode] ?? '未知';
        $warehouseStatusTxt = $warehouseStatus === 1 ? '已冻结' : '未冻结';

        $alert = '';
        if ($statusCode === 4 && ! empty($quota->audit_reject_reason)) {
            $alert = $quota->audit_reject_reason;
        }

        $remainingDays = null;
        $deadlineDate  = null;
        $activeDays    = $this->getCorpQuotaActiveDays((int) ($quota->uniacid ?? 1));

        if ($statusCode === 1 && ! empty($quota->apply_at)) {
            $cycleSeconds   = max(1, $activeDays * 86400);
            $elapsedSeconds = max(0, time() - (int) $quota->apply_at);
            $cycleElapsed   = $elapsedSeconds % $cycleSeconds;
            $elapsedDays    = (int) floor($cycleElapsed / 86400);
            $remainingDays  = $activeDays - $elapsedDays;
            if ($remainingDays <= 0) {
                $remainingDays = $activeDays;
            }
            $deadline     = (int) $quota->apply_at + $cycleSeconds;
            $deadlineDate = Carbon::createFromTimestamp($deadline)->toDateString();
        } elseif (! empty($quota->audit_passed_at)) {
            $cycleSeconds   = max(1, $activeDays * 86400);
            $elapsedSeconds = max(0, time() - (int) $quota->audit_passed_at);
            $cycleElapsed   = $elapsedSeconds % $cycleSeconds;
            $elapsedDays    = (int) floor($cycleElapsed / 86400);
            $remainingDays  = $activeDays - $elapsedDays;
            if ($remainingDays <= 0) {
                $remainingDays = $activeDays;
            }
            $deadline     = (int) $quota->audit_passed_at + $cycleSeconds;
            $deadlineDate = Carbon::createFromTimestamp($deadline)->toDateString();
        }

        $buttonText     = '激活授信';
        $buttonDisabled = false;
        $buttonAction   = 'activate';

        if ($statusCode === 1) {
            $buttonText   = '取消授信';
            $buttonAction = 'cancel';
        } elseif ($statusCode === 2) {
            $buttonText     = '取消授信';
            $buttonAction   = 'cancel';
            $buttonDisabled = $quota->stock_num < $quota->num || $warehouseStatus === 1;
        } elseif ($statusCode === 3) {
            $buttonText     = '取消授信';
            $buttonAction   = 'cancel';
            $buttonDisabled = true;
        } elseif ($statusCode === 4) {
            $buttonText     = '重新激活';
            $buttonAction   = 'activate';
        }

        $showCancelButton = false;
        if ($statusCode === 2 && (float) $quota->stock_num >= (float) $quota->num && $warehouseStatus === 0) {
            $showCancelButton = true;
        }
        if ($statusCode === 0 && (int) $quota->switch === 1) {
            $showCancelButton = true;
        }
        if ($statusCode === 1) {
            $showCancelButton = true;
        }

        return [
            'storeAmount'          => number_format((float) $quota->num, 2, '.', ''),
            'warehouseAmount'      => number_format((float) $quota->stock_num, 2, '.', ''),
            'storeStatus'          => $storeStatusText,
            'storeStatusCode'      => $statusCode,
            'warehouseStatus'      => $warehouseStatusTxt,
            'warehouseStatusCode'  => $warehouseStatus,
            'remainingDays'        => $remainingDays,
            'deadline'             => $deadlineDate,
            'alert'                => $alert,
            'tips'                 => '特别提醒 已冻结的云仓库存额度不能使用；',
            'buttonText'           => $buttonText,
            'buttonDisabled'       => $buttonDisabled,
            'buttonAction'         => $buttonAction,
            'showCancelButton'     => $showCancelButton,
            'switch'               => (int) $quota->switch,
            'auditRejectReason'    => $quota->audit_reject_reason,
            'auditPassedAt'        => $quota->audit_passed_at ? Carbon::createFromTimestamp($quota->audit_passed_at)->toDateTimeString() : null,
            'updatedAt'            => $quota->updated_at ? Carbon::createFromTimestamp($quota->updated_at)->toDateTimeString() : null,
            'activeDays'           => $activeDays,
        ];
    }

    /**
     * 组装云仓概览数据
     */
    private function formatWarehouseSummary(HhmCoinCorpQuota $quota): array
    {
        $scenario = $this->formatActivationScenario($quota);

        return [
            'amount'             => $scenario['warehouseAmount'],
            'warehouseAmount'    => $scenario['warehouseAmount'],
            'status'             => $scenario['warehouseStatus'],
            'status_code'        => $scenario['warehouseStatusCode'],
            'remainingDays'      => $scenario['remainingDays'],
            'deadline'           => $scenario['deadline'],
            'canTransfer'        => ((int) $quota->status === 2 && (int) $quota->stock_status === 0 && (float) $quota->stock_num > 0),
            'tips'               => $scenario['tips'],
            'storeAmount'        => $scenario['storeAmount'],
            'storeStatus'        => $scenario['storeStatus'],
            'storeStatusCode'    => $scenario['storeStatusCode'],
            'warehouseStatus'    => $scenario['warehouseStatus'],
            'warehouseStatusCode'=> $scenario['warehouseStatusCode'],
            'activeDays'         => $scenario['activeDays'],
        ];
    }

    /**
     * 组装流水数据
     */
    private function formatFlows($flows): array
    {
        $typeTexts = [
            self::FLOW_TYPE_ACTIVATION => '授信激活',
            self::FLOW_TYPE_TRANSFER   => '转出',
        ];

        return $flows->map(function (HhmCoinCorpQuotaFlow $flow) use ($typeTexts) {
            $oldCoin  = $flow->old_coin !== null ? (float) $flow->old_coin : null;
            $newCoin  = $flow->new_coin !== null ? (float) $flow->new_coin : null;
            $delta    = null;

            if ($oldCoin !== null && $newCoin !== null) {
                $delta = $newCoin - $oldCoin;
            } elseif ($flow->num !== null) {
                $delta = (float) $flow->num;
            } else {
                $delta = 0;
            }

            return [
                'id'         => (int) $flow->id,
                'type'       => (int) $flow->type,
                'type_text'  => $typeTexts[$flow->type] ?? '其他',
                'amount'     => number_format(abs($delta), 2, '.', ''),
                'direction'  => $delta >= 0 ? 'income' : 'expense',
                'remark'     => $flow->remark ?? '',
                'old_coin'   => $oldCoin,
                'new_coin'   => $newCoin,
                'created_at' => $flow->created_at ? Carbon::createFromTimestamp($flow->created_at)->toDateTimeString() : null,
            ];
        })->toArray();
    }

    /**
     * 获取门店关联的账号 UID（优先老板账号）
     */
    private function resolveStoreAccountUid(?Store $store = null, int $storeId = 0): int
    {
        if (! $store && $storeId > 0) {
            $store = Store::select(['id', 'boss_uid', 'uid'])->find($storeId);
        }

        if (! $store) {
            return 0;
        }

        $uid = (int) ($store->boss_uid ?: $store->uid);
        return $uid > 0 ? $uid : 0;
    }

    /**
     * 构建需要匹配流水的 send/rec 标识（兼容历史数据）
     */
    private function buildStoreFlowIdentifiers(int $storeId, ?Store $store = null, int $userId = 0): array
    {
        $identifiers = [];

        if ($userId > 0) {
            $identifiers[] = $userId;
        }

        if ($storeId > 0) {
            $identifiers[] = $storeId;
        }

        $accountUid = $this->resolveStoreAccountUid($store, $storeId);
        if ($accountUid > 0) {
            $identifiers[] = $accountUid;
        }

        $identifiers = array_filter($identifiers, function ($value) {
            return $value > 0;
        });

        return array_values(array_unique($identifiers));
    }
}


